package net.zigin.nhi.waste.view.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSONArray;
import com.gyf.immersionbar.ImmersionBar;

import net.zigin.nhi.waste.R;
import net.zigin.nhi.waste.adapter.FilterDepartAdapter;
import net.zigin.nhi.waste.adapter.FilterStatusAdapter;
import net.zigin.nhi.waste.adapter.FilterTypeAdapter;
import net.zigin.nhi.waste.adapter.HistoryAdapter;
import net.zigin.nhi.waste.adapter.IActivityHistoryType;
import net.zigin.nhi.waste.adapter.NoDataAdapter;
import net.zigin.nhi.waste.adapter.OfficeChildrenAdapter;
import net.zigin.nhi.waste.adapter.OfficeParentAdapter;
import net.zigin.nhi.waste.bean.DepartBean;
import net.zigin.nhi.waste.bean.HistoryBean;
import net.zigin.nhi.waste.constants.Constants;
import net.zigin.nhi.waste.net.ApiCall;
import net.zigin.nhi.waste.net.BaseResponse;
import net.zigin.nhi.waste.net.HttpRetrofitClient;
import net.zigin.nhi.waste.net.PublicService;
import net.zigin.nhi.waste.utils.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.paperdb.Paper;
import io.reactivex.Observable;

public class FilterDialog extends Dialog {

    private View mViewNone;
    private Button mClose;
    private RecyclerView mRvType;
    private RecyclerView mRvState;
    private RecyclerView mRvParent;
    private RecyclerView mRvChildren;
    private EditText mSearch;
    private Button mConfirm;
    private Activity activity;
    private HistoryAdapter adapter;
    private RecyclerView mRvHistory;
    private NoDataAdapter noDataAdapter = new NoDataAdapter();

    private List<String> typeList = new ArrayList<>();
    private List<String> statusList = new ArrayList<>();
    private List<String> departList = new ArrayList<>();
    private Map<String, Object> map;
    private IActivityHistoryType dd;

    private int count = 0;  //计数getDepartName()方法重复执行了几次
    private List<String> parentList = new ArrayList<>();
    private List<String> nameList = new ArrayList<>();
    private List<String> idList = new ArrayList<>();
    private String departName = "";
    private String parentId = "";
    private List<String> parentIdList = new ArrayList<>();

    public static FilterDialog mInstance;

    public FilterDialog(@NonNull Context context, Activity activity, RecyclerView mRvHistory, HistoryAdapter adapter, Map<String, Object> map, IActivityHistoryType dd) {
        super(context);
        this.activity = activity;
        this.mRvHistory = mRvHistory;
        this.adapter = adapter;
        this.map = map;
        this.dd = dd;
    }

    //单例保证每次弹出的dialog唯一
    public static FilterDialog getInstance(Context context, Activity activity, RecyclerView mRvHistory, HistoryAdapter adapter, Map<String, Object> map, IActivityHistoryType dd) {
        if (mInstance == null) {
            synchronized (FilterDialog.class) {
                if (mInstance == null) {
                    mInstance = new FilterDialog(context, activity, mRvHistory, adapter, map, dd);
                }
            }
        }
        return mInstance;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_filter);
        initView();
        initData();
    }

    private void initView() {
        ImmersionBar.with(activity, this).init();
        mViewNone = findViewById(R.id.view_none);
        mClose = findViewById(R.id.close);
        mRvType = findViewById(R.id.rv_type);
        mRvState = findViewById(R.id.rv_state);
        mRvParent = findViewById(R.id.rv_parent);
        mRvChildren = findViewById(R.id.rv_children);
        mConfirm = findViewById(R.id.confirm);
        mSearch = findViewById(R.id.search);

        Window window = this.getWindow();
        window.setBackgroundDrawable(null);
        // 设置宽高
        window.setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        // 设置弹出的动画效果
        window.setWindowAnimations(R.style.AnimBottom);
        mViewNone = window.findViewById(R.id.view_none);
        mViewNone.getBackground().setAlpha(0);

        LinearLayoutManager manager = new LinearLayoutManager(activity);
        manager.setOrientation(RecyclerView.HORIZONTAL);
        mRvParent.setLayoutManager(manager);
        mRvChildren.setLayoutManager(new LinearLayoutManager(activity));
    }


    @SuppressLint("NotifyDataSetChanged")
    private void initData() {
        mViewNone.setOnClickListener(v -> {
            dismiss();
            ImmersionBar.destroy(activity, this);
        });

        mClose.setOnClickListener(v -> {
            dismiss();
            ImmersionBar.destroy(activity, this);
        });

        typeList.add("全部");
        typeList.add("化学性医废");
        typeList.add("感染性医废");
        typeList.add("损伤性医废");
        typeList.add("病理性医废");
        typeList.add("药物性医废");
        FilterTypeAdapter typeAdapter = new FilterTypeAdapter(typeList);
        mRvType.setLayoutManager(new GridLayoutManager(activity, 3));
        mRvType.setAdapter(typeAdapter);
        typeAdapter.setPosition(0);
        typeAdapter.setGetListener((position, text) -> {
            typeAdapter.setPosition(position);
            typeAdapter.notifyDataSetChanged();

            switch (text) {
                case "全部":
                    //选全部时去除选中的医废类型记录
                    map.remove("wasteClassifyCode");
                    Paper.book().delete(Constants.WASTE_CLASSIFY_CODE);
                    break;
                case "化学性医废":
                    //记录下选中的医废类型
                    map.put("wasteClassifyCode", "chemical");
                    Paper.book().write(Constants.WASTE_CLASSIFY_CODE, "chemical");
                    break;
                case "损伤性医废":
                    map.put("wasteClassifyCode", "injury");
                    Paper.book().write(Constants.WASTE_CLASSIFY_CODE, "injury");
                    break;
                case "病理性医废":
                    map.put("wasteClassifyCode", "pathology");
                    Paper.book().write(Constants.WASTE_CLASSIFY_CODE, "pathology");
                    break;
                case "感染性医废":
                    map.put("wasteClassifyCode", "infection");
                    Paper.book().write(Constants.WASTE_CLASSIFY_CODE, "infection");
                    break;
                case "药物性医废":
                    map.put("wasteClassifyCode", "drug");
                    Paper.book().write(Constants.WASTE_CLASSIFY_CODE, "drug");
                    break;
            }

        });

        statusList.add("全部");
        statusList.add("未入库");
        statusList.add("已入库");
        statusList.add("已出库");
        FilterStatusAdapter statusAdapter = new FilterStatusAdapter(statusList);
        mRvState.setLayoutManager(new GridLayoutManager(activity, 3));
        mRvState.setAdapter(statusAdapter);
        statusAdapter.setPosition(0);
        statusAdapter.setGetListener((position, text) -> {
            statusAdapter.setPosition(position);
            statusAdapter.notifyDataSetChanged();

            switch (text) {
                case "全部":
                    //选全部时去除状态
                    map.remove("status");
                    Paper.book().delete(Constants.WASTE_STATUS);
                    break;
                case "未入库":
                    //记录下当前选中的状态
                    map.put("status", "do_collect");
                    Paper.book().write(Constants.WASTE_STATUS, "do_collect");
                    break;
                case "已入库":
                    map.put("status", "in_depot");
                    Paper.book().write(Constants.WASTE_STATUS, "in_depot");
                    break;
                case "已出库":
                    map.put("status", "out_depot");
                    Paper.book().write(Constants.WASTE_STATUS, "out_depot");
                    break;
            }
        });

        getDepartName();

        mConfirm.setOnClickListener(v -> {
            map.put("isPage", true);
            map.put("pageIndex", 1);
            map.put("pageSize", 20);
            if (StringUtil.isNotEmpty(mSearch.getText().toString())) {
                map.put("ckCode", mSearch.getText().toString());
            } else {
                map.remove("ckCode");
            }
            Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                    .getHistory(Paper.book().read(Constants.TOKEN), map);
            HttpRetrofitClient.execute(observable, new ApiCall<String>() {
                @Override
                protected void success(String data) {
                    if (StringUtil.isNotEmpty(data)) {
                        Log.i("医废追溯", data);
                        List<HistoryBean> historyList = JSONArray.parseArray(data, HistoryBean.class);
                        if (historyList != null && historyList.size() > 0) {
                            adapter.notifyData(historyList);
                            dd.upDataUi(historyList);
                        } else {
                            mRvHistory.setAdapter(noDataAdapter);
                        }
                    } else {
                        mRvHistory.setAdapter(noDataAdapter);
                    }
                    dismiss();
                }
            });
        });

    }

    /**
     * 获取科室列表
     */
    private void getDepartName() {
        Observable<BaseResponse<String>> observable = HttpRetrofitClient.getInstance().create(PublicService.class)
                .getDepartByHospitalBaseId(Paper.book().read(Constants.TOKEN), parentId);
        HttpRetrofitClient.execute(observable, new ApiCall<String>() {
            @SuppressLint("NotifyDataSetChanged")
            @Override
            protected void success(String data) {
                if (StringUtil.isNotEmpty(data)) {
                    Log.i("科室列表", data);
                    List<DepartBean> beanList = JSONArray.parseArray(data, DepartBean.class);
                    if (beanList != null && beanList.size() > 0) {
                        nameList.clear();
                        idList.clear();
                        for (DepartBean departBean : beanList) {
                            nameList.add(departBean.getName());
                            idList.add(departBean.getId());
                        }

                        parentList.add("请选择");
                        OfficeParentAdapter parentAdapter = new OfficeParentAdapter(parentList);
                        mRvParent.setAdapter(parentAdapter);
                        parentAdapter.setPosition(count);
                        parentAdapter.setGetListener((position, text) -> {
                            parentAdapter.setPosition(position);
                            parentAdapter.notifyDataSetChanged();
                            if (position == 0) {
                                parentId = "";
                                parentIdList.clear();
                                map.remove("hospitalDepartId");
                                Paper.book().delete(Constants.HOSPITAL_DEPART_ID);
                            } else {
                                parentId = parentIdList.get(position - 1);
                            }

                            List<String> newList = new ArrayList<>();
                            for (int i = 0; i < parentList.size(); i++) {
                                if (i >= position) {
                                    newList.add(parentList.get(i));
                                    count = position;
                                }
                            }
                            parentList.removeAll(newList);
                            getDepartName();
                        });

                        if (nameList.size() > 0) {
                            OfficeChildrenAdapter childrenAdapter = new OfficeChildrenAdapter(nameList);
                            mRvChildren.setAdapter(childrenAdapter);
                            childrenAdapter.setGetListener((position, text) -> {
                                childrenAdapter.setPosition(position);
                                childrenAdapter.notifyDataSetChanged();

                                departName = nameList.get(position);
                                //将第一层赋值成选中的
                                if (nameList.contains(parentList.get(count)) || parentList.get(count).equals("请选择")) {
                                    parentList.remove(count);
                                }
                                parentList.add(departName);
                                parentAdapter.notifyDataSetChanged();

                                parentId = idList.get(position);
                                parentIdList.add(parentId);
                                getDepartName();
                                count++;

                                map.put("hospitalDepartId", parentId);
                                Paper.book().write(Constants.HOSPITAL_DEPART_ID, parentId);
                            });
                        }
                    } else {
                        count = 0;
                    }
                }
            }
        });
    }

}
